package com.atguigu.gmall.realtime.dwd.db.app;

import com.atguigu.gmall.realtime.common.base.BaseSQLApp;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.SQLUtil;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class DwdInteractionCommentInfo extends BaseSQLApp {
    public static void main(String[] args) {
        new DwdInteractionCommentInfo().start(10012, 4 , Constant.TOPIC_DWD_INTERACTION_COMMENT_INFO);
    }
    @Override
    public void handle(StreamExecutionEnvironment env, StreamTableEnvironment tableEnv) {
        // TODO 3.从kafka的topic_db中读取数据创建动态表---kafka连接器
        readOdsDb(tableEnv, "dwd_interaction_comment_info");
        //tableEnv.executeSql("select * from topic_db").print();
        // TODO 4.过滤出评论数据 table='comment_info' type='insert'
        Table commentInfo = tableEnv.sqlQuery("select \n" +
                "  `data`['id'] id,\n" +
                "  `data`['user_id'] user_id,\n" +
                "  `data`['sku_id'] sku_id,\n" +
                "  `data`['appraise'] appraise,\n" +
                "  `data`['comment_txt'] comment_txt,\n" +
                "  ts\n," +
                "  pt\n" +
                "from topic_db where `table`='comment_info' and `type`='insert'");
        tableEnv.createTemporaryView("comment_info",commentInfo);
        //tableEnv.executeSql("select * from comment_info").print();
        // TODO 5.从HBase中读取字典表数据创建动态表---HBase连接器
        readBaseDic(tableEnv);
        tableEnv.executeSql("select dic_code,dic_name from base_dic").print();
        // TODO 6.关联评论和字典数据---lookup join
        Table joinedTable = tableEnv.sqlQuery("SELECT \n" +
                "  id,user_id,sku_id,appraise,dic.dic_name as appraise_name,comment_txt,ts\n" +
                "  FROM comment_info AS c\n" +
                "  JOIN base_dic FOR SYSTEM_TIME AS OF c.pt AS dic\n" +
                "   ON c.appraise = dic.dic_code");
        //joinedTable.execute().print();
        // TODO 7.将关联的结果写道kafka主题中---upsert-kafka连接器
        tableEnv.executeSql("CREATE TABLE " + Constant.TOPIC_DWD_INTERACTION_COMMENT_INFO + " (\n" +
                "  id string,\n" +
                "  user_id string,\n" +
                "  sku_id string,\n" +
                "  appraise string, \n" +
                "  appraise_name string, \n" +
                "  comment_txt string,\n" +
                "  ts bigint,\n" +
                "  PRIMARY KEY (id) NOT ENFORCED\n" +
                ")" + SQLUtil.getUpsertKafkaDDL(Constant.TOPIC_DWD_INTERACTION_COMMENT_INFO));
        joinedTable.executeInsert(Constant.TOPIC_DWD_INTERACTION_COMMENT_INFO);
    }

}
